import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from config import (
    PHONE_ALERT_ENABLED,
    PHONE_NUMBERS,
    ALIYUN_ACCESS_KEY,
    ALIYUN_ACCESS_SECRET,
    ALIYUN_CALLING_NUMBER
)

class PhoneAlertService:
    def __init__(self):
        if not PHONE_ALERT_ENABLED:
            return
            
        if not (ALIYUN_ACCESS_KEY and ALIYUN_ACCESS_SECRET):
            print("警告: 阿里云访问凭证未配置，电话预警功能将不可用")
            return
            
        self.client = AcsClient(
            ALIYUN_ACCESS_KEY,
            ALIYUN_ACCESS_SECRET,
            'cn-hangzhou'
        )
    
    def make_voice_call(self, alert_message):
        """发起语音通知"""
        if not PHONE_ALERT_ENABLED or not self.client:
            return
            
        if not PHONE_NUMBERS:
            print("警告: 未配置接收电话号码，无法发送语音通知")
            return
            
        for phone_number in PHONE_NUMBERS:
            if not phone_number.strip():
                continue
                
            request = CommonRequest()
            request.set_accept_format('json')
            request.set_domain('dyvmsapi.aliyuncs.com')
            request.set_method('POST')
            request.set_protocol_type('https')
            request.set_version('2017-05-25')
            request.set_action_name('SingleCallByTts')
            
            request.add_query_param('CalledNumber', phone_number)
            request.add_query_param('CallingNumber', ALIYUN_CALLING_NUMBER)
            request.add_query_param('TtsCode', 'TTS_000000')
            request.add_query_param('TtsParam', json.dumps({'message': alert_message}))
            
            try:
                response = self.client.do_action_with_exception(request)
                print(f"语音通知已发送到 {phone_number}")
            except Exception as e:
                print(f"发送语音通知到 {phone_number} 失败: {str(e)}")